import logging
import os

from flask import jsonify, request, send_from_directory
from werkzeug.exceptions import BadRequest, NotFound

from app.model.models import Photo
from app.utils.file_utils import FILE_PREFIX
from . import bp

LOG = logging.getLogger(__name__)


@bp.route('/photos/names', methods=['GET'])
def get_photos_names():
    user_id = request.args.get('id', default=0, type=int)
    if user_id == 0:
        raise BadRequest('Illegal Request!')
    query_result = Photo.query.with_entities(Photo.photo_name).filter_by(user_id=user_id).all()
    photo_names = [photo_name for photo_name, in query_result]
    return jsonify(success=True, data=photo_names, status_code=200)


@bp.route('/photo/<path:photo_name>', methods=['GET'])
def get_photo(photo_name):
    data_path = os.path.join(FILE_PREFIX, photo_name)
    if not os.path.exists(data_path):
        return NotFound()
    return send_from_directory(FILE_PREFIX, photo_name, mimetype='image/webp', as_attachment=False)
